package com.leetcode.p100;

import com.bean.ListNode;
import com.utils.DataUtils;

public class Test148 {

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;

        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode middleNode = slow.next;
        slow.next = null;

        ListNode left = sortList(head);
        ListNode right = sortList(middleNode);

        return merge(left, right);
    }

    private ListNode merge(ListNode left, ListNode right) {
        if (null == left) {
            return right;
        }
        if (right == null) {
            return left;
        }

        ListNode dummyNode = new ListNode();
        ListNode cur = dummyNode;

        while (left != null && right != null) {
            if (left.val < right.val) {
                cur.next = left;
                left = left.next;
            } else {
                cur.next = right;
                right = right.next;
            }
            cur = cur.next;
        }

        if (left == null) cur.next = right;
        if (right == null) cur.next = left;

        return dummyNode.next;
    }

    public static void main(String[] args) {
        ListNode listNode1 = DataUtils.getListNode(new int[]{4, 5, -1, 2, 9, 3, 11, 1});

        Test148 test = new Test148();
        ListNode list = test.sortList(listNode1);
        DataUtils.printListNode(list);
    }

}
